//
//  GRPayBillViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/8/25.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRPayBillViewController.h"
#import "GRStoreAction.h"
#import "GRPayPointConfirmView.h"
#import "GRPayWayView.h"
#import "GRPayOrderDatailVC.h"
#import <YYKeyboardManager/YYKeyboardManager.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "GRScanViewController.h"
#import "GRBlankSpace.h"
#import "GRXCouponsModel.h"
#import "GRCouponsTableViewController.h"
#import "GRXCouponsModel.h"
#import "GRGiveQuotaTipView.h"
@interface GRPayBillViewController ()<GRPayWayViewDelegate ,GRPayPointConfirmViewDelegate,GRPayManagerDelegate,YYKeyboardObserver,GRCouponsTableViewControllerDelegate>
{
    NSInteger payId;
    CGFloat pointRate;
    BOOL firstPay;
    CGFloat GRPrice ;
    CGFloat discount ;
    BOOL useCoupons;
    CGFloat giveQuota;
    CGFloat rate;
    CGFloat reduce;
    CGFloat giveDiscount;
   
    
    
}

@property (weak, nonatomic) IBOutlet UILabel *nickNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UITextField *priceTF;
@property (weak, nonatomic) IBOutlet UIButton *GRBt;
@property (weak, nonatomic) IBOutlet UIButton *giveBt;


@property (weak, nonatomic)
IBOutlet UILabel *totalPointLabel;
@property (weak, nonatomic) IBOutlet UILabel *usePointLabel;
@property (weak, nonatomic) IBOutlet UILabel *atcPayLabel;
@property(nonatomic,assign)CGFloat point;
@property (weak, nonatomic) IBOutlet UIButton *confirmBt;
@property(nonatomic,strong)GRPayPointConfirmView *payPointConfirmView;

@property (nonatomic,strong) IBOutlet UIScrollView *mainScrollerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topOffset;

@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;

@property (weak, nonatomic) IBOutlet UILabel *discountLabel;
@property(nonatomic,strong)NSDictionary * shardBounty;

@property (weak, nonatomic) IBOutlet UILabel *giveQuotaLabel;

@property (strong, nonatomic) IBOutlet UIView *mainView;
@property(nonatomic,strong)GRBlankSpace *blankSpace;
@property(nonatomic,strong)NSArray * coupousArr;
@property(nonatomic,strong) GRXCouponsModel * couponsModel;
@property(nonatomic,strong)GRXCouponsModel *selectedModel;
@property (weak, nonatomic) IBOutlet UILabel *reduceLabel;

@end

@implementation GRPayBillViewController
-(GRBlankSpace *)blankSpace {
    if (!_blankSpace) {
        _blankSpace = [GRBlankSpace loadFromNib];
        _blankSpace.frame  = self.view.bounds;
        _blankSpace.hidden = YES;
        _blankSpace.contentMode = GRBlankContentModeInvalidShop;
        [self.view addSubview:_blankSpace];
    }
    return _blankSpace;
}
-(BOOL)navigationShouldPopOnBackButton{
    BOOL isScan = NO;
    for (UIViewController * controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[GRScanViewController class]]) {
            isScan = YES;
        }
    }
    if (isScan) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        return NO;
    }
    return YES;
}




-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[YYKeyboardManager defaultManager] addObserver:self];
    //TODO: 页面appear 禁用
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
        [[YYKeyboardManager defaultManager] removeObserver:self];
    //TODO: 页面Disappear 启用
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.priceTF becomeFirstResponder];

}

-(GRPayPointConfirmView *)payPointConfirmView{
    if (!_payPointConfirmView) {
        _payPointConfirmView  = [GRPayPointConfirmView xx_instantiateFromNib];
        _payPointConfirmView.delegate = self;
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_payPointConfirmView];
        [_payPointConfirmView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(window);
        }];
    }
    return _payPointConfirmView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"龟米";
    if (!_isValid) {
        self.blankSpace.hidden = NO;
        return;
    }
    useCoupons = YES;
    pointRate = 1.0;
    discount = 0.0;
    GRPrice = 0.0;
    giveDiscount = 0.0;
    [self readyPayTheBill];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.priceTF];
    [GRPayManager sharePay].delegate = self;
    if (@available(iOS 11.0, *)) {
        self.mainScrollerView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
    self.automaticallyAdjustsScrollViewInsets = NO;
    //增加监听，当键盘出现或改变时收出消息
    }
    
    
}
-(void)keyboardChangedWithTransition:(YYKeyboardTransition)transition{
        //获取键盘的高度
    CGRect kbRect = [[YYKeyboardManager defaultManager] convertRect:transition.toFrame toView:self.view];
     if ([YYKeyboardManager defaultManager].keyboardVisible) {
        
         self.mainScrollerView.height = KscreenHeight -kbRect.size.height-68;
         self.mainScrollerView.contentOffset = CGPointMake(0, self.mainScrollerView.contentSize.height >=self.mainScrollerView.height?self.mainScrollerView.contentSize.height-self.mainScrollerView.height:0);

     }else{
          [UIView animateWithDuration:0.25 animations:^{
              self.mainScrollerView.height= KscreenHeight;
              self.mainScrollerView.contentOffset = CGPointZero;
              
          }];
     }
}


-(void)textChange{
    discount = 0.0;
   [self changePrice:nil];
    if ([self.priceTF.text floatValue] >0) {
        self.confirmBt.userInteractionEnabled = YES;
        self.confirmBt.backgroundColor = HEXCOLOR(0xFBD62D);
        [self.confirmBt setTitleColor:HEXCOLOR(0x222222) forState:UIControlStateNormal];
    
        self.priceTF.font = [UIFont boldSystemFontOfSize:35];
        
    }else{
        if (self.priceTF.text.length == 0) {
              self.priceTF.font = [UIFont systemFontOfSize:18];
        }else{
             self.priceTF.font = [UIFont boldSystemFontOfSize:35];
        }
        if (self.priceTF.text.length ==1&& [[self.priceTF.text substringToIndex:1] isEqualToString:@"."]) {
            self.priceTF.text = @"0.";
        }
       self.confirmBt.userInteractionEnabled = NO;
        self.confirmBt.backgroundColor = HEXCOLOR(0xEEEEEE);
        [self.confirmBt setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.atcPayLabel.text = @"0.00";
    }
}
-(void)readyPayTheBill{
    [GRStoreAction readyPayTheBillWithStoreId:self.storeId ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        NSLog(@"%@",responseObject);
        if (success) {
        pointRate = [responseObject[@"pointRate"] floatValue];
        self.nickNameLabel.text = responseObject[@"nikeName"];
        self.addressLabel.text = responseObject[@"addr"];
        giveQuota = [responseObject[@"giveQuota"] floatValue];
        self.giveQuotaLabel.text = [NSString stringWithFormat:@"赠送额度￥%.2lf",giveQuota];
        self.totalPointLabel.text = [NSString stringWithFormat:@"龟米积分%.2lf",[responseObject[@"point"] floatValue]];
        self.point = [responseObject[@"point"] floatValue];
        [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"avatar"]] placeholderImage:[UIImage imageNamed:@""]];
            rate = [responseObject[@"rate"]floatValue];
        self.topOffset.constant = self.point >0?212:142;
        self.mainScrollerView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, KscreenWidth,  self.point >0?453:383)];
        self.mainScrollerView.contentSize = CGSizeMake(KscreenWidth, self.point >0?418:348);
        [self.view addSubview:self.mainScrollerView];

        [self.mainScrollerView addSubview:self.mainView];
        WEAKSELF
        [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.mainScrollerView.mas_left);
            make.width.mas_equalTo(@(KscreenWidth));
            make.height.mas_equalTo(@(weakSelf.point >0?453:383));
            make.top.equalTo(weakSelf.mainScrollerView.mas_top);
        }];
             NSMutableArray * arr = [NSMutableArray array];
        if ([responseObject[@"shardBounty"] isKindOfClass:[NSNull class]]) {//有没有新人红包

        }else{
             self.couponsModel = [GRXCouponsModel yy_modelWithDictionary:responseObject[@"shardBounty"]];
            self.couponsModel.type = 4;
            [arr addObject:self.couponsModel];
        }
            if (Array(responseObject[@"vouchers"])) {
            for (NSDictionary * dic in responseObject[@"vouchers"]) {
                GRXCouponsModel * couponsModel = [GRXCouponsModel yy_modelWithDictionary:dic];
                [arr  addObject:couponsModel];
            }
        }
            self.coupousArr = arr;
        }else{
            self.blankSpace.hidden = NO;
        }
    }];
}
- (IBAction)changePrice:(UIButton *)sender {
    if (sender) {
           sender.selected = !sender.selected;
    }
      self.discountLabel.textColor = HEXCOLOR(0xDF0202);
    if (self.couponsModel&&!firstPay&&useCoupons) {//存在新人红包
        if ([self.priceTF.text floatValue]>= self.couponsModel.doorsill) {
            self.discountLabel.text = [NSString stringWithFormat:@"-%.lf",self.couponsModel.discount];
            discount = self.couponsModel.discount;
            _selectedModel = self.couponsModel;
        }else{
             discount = 0.0;
            _selectedModel = nil;

            self.discountLabel.text = @"无可用劵";
            self.discountLabel.textColor = HEXCOLOR(0x999999);
        }
    }else{
        if (discount != 0.0) {
            self.discountLabel.text = [NSString stringWithFormat:@"-%.lf",discount];
        }else{
        NSInteger page = 0;
        for (int i = 0 ; i < self.coupousArr.count; i++) {
            GRXCouponsModel * model = self.coupousArr[i];
            if ([self.priceTF.text floatValue] >= model.doorsill) {
                page += 1;
            }
        }
        if (page >0) {
            self.discountLabel.text = [NSString stringWithFormat:@"%d张可用",page];
        }else{
            self.discountLabel.text = @"无可用劵";

            self.discountLabel.textColor = HEXCOLOR(0x999999);
            discount = 0.0;
            _selectedModel = nil;
        }
    }
    }
    if (self.giveBt.selected) {
    if (self.selectedModel != nil&&self.selectedModel.type != 4) {
        giveDiscount = ([self.priceTF.text floatValue] -discount ) *(1-rate);

    }else{
        giveDiscount = [self.priceTF.text floatValue]  * (1-rate);
    }
    }else{
        giveDiscount = 0;
        
    }
    self.reduceLabel.text = [NSString stringWithFormat:@"本次-￥%.2lf",giveDiscount];
    self.reduceLabel.textColor = giveDiscount >0 ?HEXCOLOR(0xDF0202):HEXCOLOR(0x999999);
    if (self.GRBt.selected) {
   
        if ([self.priceTF.text floatValue]-discount-giveDiscount >=self.point *pointRate) {
            self.usePointLabel.text = [NSString stringWithFormat:@"-￥%.2lf",self.point *pointRate];
            GRPrice = self.point;
        }else{
            self.usePointLabel.text = [NSString stringWithFormat:@"-￥%.2lf",[self.priceTF.text floatValue]-discount-giveDiscount];
            GRPrice = fabs(([self.priceTF.text floatValue]-discount-giveDiscount)/pointRate);
        }
    }else{
        GRPrice = 0;
        self.usePointLabel.text = @"￥-0.00";
    }
    
   

    if ([self.priceTF.text floatValue]- GRPrice - discount-giveDiscount >=0) {
           self.atcPayLabel.text = [NSString stringWithFormat:@"%.2lf",[self.priceTF.text floatValue]- GRPrice*pointRate - discount-giveDiscount];
    }else{
        self.atcPayLabel.text = @"0.00";
    }
    

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)payAction:(id)sender {
    [self.priceTF resignFirstResponder];
    if ([self.atcPayLabel.text floatValue] >0) {
        self.payPointConfirmView.hidden = YES;
        [GRPayWayView show:[self.atcPayLabel.text floatValue]  Delegate:self];
    }else{
        self.payPointConfirmView.hidden = NO;
        self.payPointConfirmView.payPricelabel.text = self.atcPayLabel.text;
        self.payPointConfirmView.topOffset.constant = 51;
        self.payPointConfirmView.firstBuyView.hidden = NO;
        self.payPointConfirmView.redPriceLabel.text = [NSString stringWithFormat:@"-￥%.2lf",discount];
        self.payPointConfirmView.originalPriceLabel.text =  [NSString stringWithFormat:@"￥%.2lf",[self.priceTF.text floatValue]];
        self.payPointConfirmView.pointLabel.text = [NSString stringWithFormat:@"-￥%.2lf", GRPrice*pointRate];
    }
}

-(void)confirmPayAction{
     self.payPointConfirmView.hidden = YES;
    [self payOrdertWithPayType:1];
    
}

-(void)payOrdertWithPayType:(NSInteger)payType{
    NSDictionary * dic = @{
                           @"costPoint": self.GRBt.selected? [NSString stringWithFormat:@"%.2lf",GRPrice]:@"0",
        @"payMoney":[NSString stringWithFormat:@"%.2lf",[self.atcPayLabel.text floatValue]],
        @"payType":payType == 1?@"point":payType == 2?@"alipay":@"wechat",
        @"profileOnePayId":@(self.storeId),
        @"source":@"ios",
        @"shardBountyId": (self.selectedModel&&self.selectedModel.type==4)?@(self.selectedModel.id):@"",
        @"totalMoney":[NSString stringWithFormat:@"%.2lf",[self.priceTF.text floatValue]],
        @"voucherId":(self.selectedModel&&self.selectedModel.type!=4)?@(self.selectedModel.id):@"",
                           @"giveDiscount":[NSString stringWithFormat:@"%.2lf",giveDiscount]
                           
        };
    [GRStoreAction  payOrder:dic  ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        NSLog(@"%@", responseObject);
        if (success) {
             payId = [responseObject[@"orderId"] integerValue];
            if (payType == 1) {
                [self paySuccess];
            }else{
                if (payType == 2) {
                    [[GRPayManager sharePay] aliPay: responseObject[@"body"]];
                }else{
                    [GRPayManager WeChatPay:responseObject];
                }
            }
        }else{
            [GRHUD showMessage:error.errorMsg];
        }
    }];
    
}
/**
 微信支付
 
 @param payResp <#payResp description#>
 */
- (void)wechatPayResp:(BaseResp *)payResp{
    switch (payResp.errCode){
        case WXSuccess:{
            NSLog(@"支付成功");
            [self paySuccess];
        }
            break;
        case WXErrCodeUserCancel:{
            NSLog(@"已中断支付");
        }
            break;
        default:{
            NSLog(@"支付失败");
        }
            break;
    }
    NSLog(@"微信支付");
    
    
}

/**
 支付宝支付
 
 @param resultDic <#resultDic description#>
 */
- (void)alipayResultDic:(NSDictionary *)resultDic{
    if ([resultDic[@"resultStatus"] isEqual:@"9000"]) {
        NSLog(@"支付成功");
        [self paySuccess];
    }else if ([resultDic[@"resultStatus"] isEqual:@"6001"]){
        NSLog(@"已中断支付");
        
    }else{
        NSLog(@"支付失败");
    }
}

- (IBAction)couponsAction:(UIButton *)sender {
  
    GRCouponsTableViewController * couponsVC = [[GRCouponsTableViewController alloc]init];
    couponsVC.delegate = self;
    couponsVC.couponsType = 3;
    couponsVC.seletedModel = self.selectedModel;
    couponsVC.storeId = self.storeId;
    couponsVC.doorlish = [self.priceTF.text floatValue];
    [self.navigationController pushViewController:couponsVC animated:YES];
}

-(void)selectedCouponsModel:(GRXCouponsModel *)model{
    if (!firstPay) {
        firstPay = YES;
    }
    discount = model.discount;
    _selectedModel = model;
    [self changePrice:nil];

    useCoupons = YES;
}

-(void)seltedNoCouponsModel{
    discount = 0.0;
    _selectedModel = nil;
    useCoupons = NO;
    [self changePrice:nil];
   

    
}

-(void)paySuccess {
    [self readyPayTheBill];
    [GRHUD showMessage:@"买单成功"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"freshList" object:self userInfo:nil];
    
    GRPayOrderDatailVC * successVC = [[GRPayOrderDatailVC alloc]init];
    successVC.orderId = payId;
    successVC.isPay = YES;
    [self.navigationController pushViewController:successVC animated:YES];
}

- (IBAction)showTip:(id)sender {
    [GRGiveQuotaTipView show];
}


/*
#pragma mark - Navigativ  

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
